package org.porridge.util.error;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;








import jodd.mail.Email;
import jodd.mail.EmailAttachment;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpSslServer;

import org.porridge.util.Constant;
import org.porridge.util.EmailUitl;
import org.transmit.util.FileUtil;



public class errorMail {
   
    public static String getIpAddr(HttpServletRequest request) {
    	 String ip = request.getHeader("x-forwarded-for");
    	 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	  ip = request.getHeader("Proxy-Client-IP");
    	 }
    	 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	  ip = request.getHeader("WL-Proxy-Client-IP");
    	 }
    	 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	  ip = request.getRemoteAddr();
    	 }
    	 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	  ip = request.getHeader("http_client_ip");
    	 }
    	 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	  ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    	 }
    	 if (ip != null && ip.indexOf(",") != -1) {
    	  ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
    	 }
    	 return ip;
    	}
    /**
     * 获得错误信息
     * @param req
     * @return
     */
    private static Throwable _GetException(HttpServletRequest req) {
    	if(req == null) return null;
    	Throwable t = (Throwable)req.getAttribute("javax.servlet.jsp.jspException");
    	if(t==null){
    		t = (Throwable)req.getAttribute("javax.servlet.error.exception");
    	}
    	return t;
    }
    public static void reportError(HttpServletRequest req){
    	Throwable t =_GetException(req);
    	new EmailUitl(0,getErrorHtml(req,t)).start();
    }

    /**
     * 格式化错误信息
     * @param req
     * @param t 错误信息
     * @param site 出错的个人空间
     * @return
     * <h2>Request Headers</h2>
     */
    @SuppressWarnings("rawtypes")
    public static String getErrorHtml(HttpServletRequest req, Throwable t) {
    	StringBuilder html = new StringBuilder();
    	if(req != null){
    		html.append("<h2>Request Headers</h2><table>");	
    		html.append("<tr><th>Request URL</th><td>");
    		html.append(req.getRequestURL().toString());
    		if(req.getQueryString()!=null){
    			html.append('?');
    			html.append(req.getQueryString());						
    		}
    		html.append("</td></tr>");
    		html.append("<tr><th>Remote Addr</th><td>");
    		html.append(getIpAddr(req));
    		html.append("</td></tr>");
    		html.append("<tr><th>Request Method</th><td>");
    		html.append(req.getMethod());
    		html.append("</td></tr>");
    		html.append("<tr><th>CharacterEncoding</th><td>");
    		html.append(req.getCharacterEncoding());
    		html.append("</td></tr>");
    		html.append("<tr><th>Request Locale</th><td>");
    		html.append(req.getLocale());
    		html.append("</td></tr>");
    		html.append("<tr><th>Content Type</th><td>");
    		html.append(req.getContentType());
    		html.append("</td></tr>");
    		Enumeration headers = req.getHeaderNames();
    		while(headers.hasMoreElements()){
    			String key = (String)headers.nextElement();
    			html.append("<tr><th>");
    			html.append(key);
    			html.append("</th><td>");
    			html.append(req.getHeader(key));
    			html.append("</td></tr>");
    		}		
    		html.append("</table><h2>Request Parameters</h2><table>");		
    		Enumeration params = req.getParameterNames();
    		while(params.hasMoreElements()){
    			String key = (String)params.nextElement();
    			html.append("<tr><th>");
    			html.append(key);
    			html.append("</th><td>");
    			html.append(req.getParameter(key));
    			html.append("</td></tr>");
    		}
    		html.append("</table>");
    	}
    	html.append("<h2>");
    	html.append(t.getClass().getName());
    	html.append('(');
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
    	html.append(sdf.format(new Date()));
    	html.append(")</h2><pre>");
    	try {
    		html.append(_Exception(t));
    	} catch (IOException ex) {}
    	html.append("</pre>");

    	html.append("<h2>System Properties</h2><table>");		
    	Set props = System.getProperties().keySet();
    	for(Object prop : props){
    		html.append("<tr><th>");
    		html.append(prop);
    		html.append("</th><td>");
    		html.append(System.getProperty((String)prop));
    		html.append("</td></tr>");
    	}
    	html.append("</table>");
    	return html.toString();
    }


    /**
     * 将异常信息转化成字符串
     * @param t
     * @return
     * @throws IOException 
     */
    private static String _Exception(Throwable t) throws IOException{
    	if(t == null)
    		return null;
    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	try{
    		t.printStackTrace(new PrintStream(baos));
    	}finally{
    		baos.close();
    	}
    	return baos.toString();
    }
}
